package br.com.salao.model;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

import org.apache.log4j.Logger;

import br.com.salao.entity.Endereco;
import br.com.salao.session.EnderecoBase;
import br.com.salao.util.Utils;

public class EnderecoModel {

	private Logger logger =  Logger.getLogger(EnderecoModel.class.getName());

	public Endereco buscarEnderecoPorLogradouro(Endereco endereco){
		try{
			logger.debug(":: EnderecoModel :: buscarEnderecoPorLogradouro() ::");
			EnderecoBase enderecoBase  = getBean();
			return enderecoBase.buscarEnderecoPorLogradouro(endereco);
		} catch (Exception e) {

			StringBuffer sb = new StringBuffer();
			sb.append(e.getMessage());
			sb.append(e.getCause());
			logger.debug(sb.toString());
			e.printStackTrace();
			
			return null;
		}
	}

	public Endereco inserir(Endereco endereco){
		try{
			logger.debug(":: EnderecoModel :: inserir() ::");
			EnderecoBase enderecoBase  = getBean();
			return enderecoBase.inserir(endereco);
		} catch (Exception e) {

			StringBuffer sb = new StringBuffer();
			sb.append(e.getMessage());
			sb.append(e.getCause());
			logger.debug(sb.toString());
			e.printStackTrace();
			
			return null;
		}
	}	
	
	public Endereco update(Endereco endereco){
		try{
			logger.debug(":: EnderecoModel :: update() ::");
			EnderecoBase enderecoBase  = getBean();
			return enderecoBase.update(endereco);
			
		} catch (Exception e) {

			StringBuffer sb = new StringBuffer();
			sb.append(e.getMessage());
			sb.append(e.getCause());
			logger.error(sb.toString());
			e.printStackTrace();
			
			return null;
		}
	}	
	
	public boolean deletar(int id){
		try{
			
			logger.debug(":: EnderecoModel :: deletar() ::");
			EnderecoBase enderecoBase  = getBean();
			enderecoBase.deletar(id);
			return true;
			
		} catch (Exception e) {

			StringBuffer sb = new StringBuffer();
			sb.append(e.getMessage());
			sb.append(e.getCause());
			logger.error(sb.toString());
			e.printStackTrace();

			return false;
		}
	}	
	
    public EnderecoBase getBean() throws Exception {
    	
    	logger.debug(":: EnderecoModel :: getBean() ::");
    	
        Properties prop = Utils.getProperties();     
        Context ctx = new InitialContext(prop); 
        Object ref = ctx.lookup(prop.getProperty("ENDERECO_LOOKUP"));       
      
        return (EnderecoBase)PortableRemoteObject.narrow(ref, EnderecoBase.class);
    }
}
